package com.smart.translator.ui.index;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.smart.translator.R;
import com.smart.translator.data.model.Language;
import java.util.List;

public class IndexFragment extends Fragment {
    private IndexViewModel viewModel;
    private EditText inputEditText;
    private TextView resultTextView, wordCountTextView, resultSrcTextView;
    private Spinner sourceLangSpinner, targetLangSpinner;
    private Button translateBtn, switchBtn, copyBtn, speakBtn, clearBtn, pasteBtn;
    private ProgressBar loadingBar;
    private LinearLayout resultArea;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        inputEditText = view.findViewById(R.id.inputEditText);
        resultTextView = view.findViewById(R.id.resultTextView);
        sourceLangSpinner = view.findViewById(R.id.sourceLangSpinner);
        targetLangSpinner = view.findViewById(R.id.targetLangSpinner);
        translateBtn = view.findViewById(R.id.translateBtn);
        switchBtn = view.findViewById(R.id.switchBtn);
        copyBtn = view.findViewById(R.id.copyBtn);
        speakBtn = view.findViewById(R.id.speakBtn);
        wordCountTextView = new TextView(requireContext());
        clearBtn = new Button(requireContext());
        pasteBtn = new Button(requireContext());
        resultSrcTextView = new TextView(requireContext());
        loadingBar = new ProgressBar(requireContext());
        resultArea = new LinearLayout(requireContext());
        ((ViewGroup) inputEditText.getParent()).addView(wordCountTextView);
        ((ViewGroup) inputEditText.getParent()).addView(clearBtn);
        ((ViewGroup) inputEditText.getParent()).addView(pasteBtn);
        ((ViewGroup) resultTextView.getParent()).addView(resultSrcTextView);
        ((ViewGroup) resultTextView.getParent()).addView(loadingBar);
        loadingBar.setVisibility(View.GONE);
        clearBtn.setText("清空");
        pasteBtn.setText("粘贴");
        resultSrcTextView.setText("");
        resultArea.setOrientation(LinearLayout.VERTICAL);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(this).get(IndexViewModel.class);
        viewModel.getLanguages().observe(getViewLifecycleOwner(), langs -> {
            ArrayAdapter<Language> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, langs);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sourceLangSpinner.setAdapter(adapter);
            targetLangSpinner.setAdapter(adapter);
        });
        viewModel.getSourceLangIndex().observe(getViewLifecycleOwner(), idx -> sourceLangSpinner.setSelection(idx));
        viewModel.getTargetLangIndex().observe(getViewLifecycleOwner(), idx -> targetLangSpinner.setSelection(idx));
        sourceLangSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) { viewModel.setSourceLangIndex(pos); }
            @Override public void onNothingSelected(AdapterView<?> parent) {}
        });
        targetLangSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) { viewModel.setTargetLangIndex(pos); }
            @Override public void onNothingSelected(AdapterView<?> parent) {}
        });
        inputEditText.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                viewModel.setSourceText(s.toString());
            }
            @Override public void afterTextChanged(Editable s) {}
        });
        viewModel.getWordCount().observe(getViewLifecycleOwner(), count -> {
            wordCountTextView.setText(count + "/5000");
        });
        clearBtn.setOnClickListener(v -> {
            viewModel.clearText();
            inputEditText.setText("");
        });
        pasteBtn.setOnClickListener(v -> {
            viewModel.pasteText();
            inputEditText.setText(viewModel.getSourceText().getValue());
        });
        viewModel.getSourceText().observe(getViewLifecycleOwner(), text -> {
            translateBtn.setEnabled(!TextUtils.isEmpty(text));
        });
        translateBtn.setOnClickListener(v -> viewModel.translate());
        viewModel.getIsTranslating().observe(getViewLifecycleOwner(), loading -> {
            loadingBar.setVisibility(loading != null && loading ? View.VISIBLE : View.GONE);
        });
        viewModel.getTranslatedText().observe(getViewLifecycleOwner(), t -> {
            resultTextView.setText(t);
            String src = viewModel.getSourceText().getValue();
            resultSrcTextView.setText(!TextUtils.isEmpty(src) ? "原文：" + src : "");
        });
        copyBtn.setOnClickListener(v -> viewModel.copyResult());
        speakBtn.setOnClickListener(v -> viewModel.speakResult());
        switchBtn.setOnClickListener(v -> viewModel.switchLanguages());
        viewModel.getError().observe(getViewLifecycleOwner(), err -> {
            if (!TextUtils.isEmpty(err)) {
                Toast.makeText(requireContext(), err, Toast.LENGTH_SHORT).show();
            }
        });
    }
} 